﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;


namespace Tanmia.Controls
{
    /// <summary>
    /// Interaction logic for ImageTool.xaml
    /// </summary>
    public partial class ImageTool : UserControl
    {
        public static readonly DependencyProperty ImageByteProperty = DependencyProperty.Register("ImageByte", typeof(byte[]), typeof(ImageTool), new FrameworkPropertyMetadata(new byte[0]));

        private System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();

        public byte[] ImageByte
        {
            get { return (byte[])GetValue(ImageByteProperty); }
            set { SetValue(ImageByteProperty, value); }
        }

        public ImageTool()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (openDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(openDialog.FileName);
                ImageByte = ImageToByteArray(image);

                imgImage.BeginInit();
                imgImage.Source = ByteArrayToImage(ImageByte);
                imgImage.EndInit();
            }
        }

        public byte[] ImageToByteArray(System.Drawing.Image imageIn)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageIn.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }

        public BitmapImage ByteArrayToImage(byte[] byteArrayIn)
        {
            BitmapImage retValu = new BitmapImage();

            retValu.BeginInit();
            retValu.StreamSource = new MemoryStream(byteArrayIn);
            retValu.EndInit();

            return retValu;
        }

        private BitmapImage BitmapC(Bitmap bitmap)
        {

            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Png);
                ms.Position = 0;
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = ms;
                bi.EndInit();

                return bi;
            }
        }
    }
}
